<template>
  <ex-dialog v-model="visible" draggable title="添加明细" width="1300" footershow="none" :contentHeight="660">
    <template #default>
      <el-container>
          <el-aside class="nopadding dialogsearch" style="width: 300px;">
          <search-form :searches="searches" :search-form="searchForm"></search-form>
            <div style="flex: auto;text-align: center;padding-left: 40px;margin-top: 15px;">
              <el-button plain type="primary" icon="el-icon-search" @click="searchHandler" :loading="loading">
                {{ $t('button.search_ok') }}
              </el-button>
              <el-button plain type="warning" icon="el-icon-brush" @click="resetHandler">{{ $t('button.search_clear') }}
              </el-button>
            </div>
          </el-aside>
          <el-main class="nopadding" style="margin-bottom: 10px;">
			  <div style="height: 10px;"></div>
            <ex-table id="assetTable" :key="elk" ref="assetSelecterTable" :columns="columns" :height="550" size="small" :url="this.$API.asset.asset.list.url" :params="form" :refs="this.$refs" :checkbox-init="checkboxInit" @columnClick="columnClickHandler"></ex-table>
            <div style="flex: auto;text-align: center;margin-top: 5px;margin-bottom: 10px;border-bottom-right-radius: 10px;">
              <el-button plain type="primary" @click="save" :loading="loading">确 定</el-button>
              <el-button plain type="info" @click="this.visible = false" :loading="loading">取 消</el-button>
            </div>
          </el-main>
        </el-container>
    </template>
	</ex-dialog>

  <data-card ref="dataCard"></data-card>
</template>

<script>
import scIconSelect from '@/components/scIconSelect'
import exDialog from '@/components/exDialog'
import ExRelTable from "@/components/exRelTable/index.vue";
import ExLabel from "@/components/exLabel/index.vue";
import ExFormItem from "@/components/exFormItem/index.vue";
import ExTable from "@/components/exTable/index.vue";
import ExSearch from "@/components/exSearch/index.vue";
import DataCard from "@/views/asset/card/card.vue";
import SearchForm from "@/components/exSearch/search_form.vue";
import http from "@/utils/request";
import {h} from "vue";
import globalparam from "@/constant/model/globalparam";

export default {
  name:"assetSelecter",
  computed: {},
  emits: ['success'],
  components: {
    SearchForm,
    DataCard,
    ExSearch, ExTable,
    ExFormItem,
    ExLabel,
    ExRelTable,
    scIconSelect,
    exDialog
  },
  props: {
    ids:{type:Array,default:[]},
    processType:{type:Object,default:null}
  },
  data() {
    return {
		elk:0,
      activeName: 'base',
      visible: false,
      form: {
      },
      model:{},
      loading: false,
      oldForm: null,
      searchForm:{},
      searches: [
        {type: "input", name: "资产编号", code: "code"},
        {type: "input", name: "资产名称", code: "name"},
        {type: "tree-select", name: "资产分类", code: "assetCategoryId",dictCode:'FamsAssetCategory',priKey:true,disabledNode:true},
        {type: "tree-select", name: "使用部门", code: "usingDepartmentId",dictCode:'SysOrganization',priKey:true},
        {type: "selector", name: "使用人", code: "usingMenId",dictCode:'SysUser',isicon:true,checkDept:false,deptIds:this.$TOOL.current.manageDeptIds()},
        {type: "daterange", name: "购置日期", code: "boughtDateStart,boughtDateEnd",valueFormat:"YYYYMMDD",format:"YYYY-MM-DD",range:30},
		{type: "switch", name: "排除车辆房产", code: "excludeCarAndHouse",ops:[false,true],showLabel:false},
      ],
      columns: [
		{code: "assetStatusId", name: "资产状态", width:"75",formatter:"DICT",key: "ASSET_STATUS"},
        {code: "code", name: "资产编码", width:"140",click:"showAsset",align:"center"},
        {code: "name", name: "资产名称", width:"200",align:"center"},

		{code: "isLocked", name: "操作状态", width:"80",click:"showDocument",formatter:"DICT",key: "IS_LOCKED"},
        {code: "isTask", name: "盘点状态", width:"75", formatter: function (row, value, _this) {
            if (value===0) {
              return h(ExLabel, {key:value,code: "EMPTY",value:'空闲',color:'#056307',border:0});
            }
            return h(ExLabel, {key:value,code: "EMPTY",value:'盘点中',color:'#C20638',border:0});
          }},
        {code: "assetCategoryId", name: "资产分类",width:"200", formatter:"DICT",key: "FamsAssetCategory",align:"center"},
        {code: "usingDepartmentId", name: "使用部门", width:"200",formatter:"DICT",key: "SysOrganization",align:"center"},
        {code: "other.disk", name: "品牌", width:"200",align:"center"},
        {code: "model", name: "规格型号", width:"250",align:"center"},
        {code: "serialCode", name: "序列号", width:"150",align:"center"},
      ],
      pageForm: {
				current: 1,
				pageSize: 30,
			},
    }
  },
  watch: {},
  mounted() {
    if(this.processType!=null){
      this.pageForm.pageSize=this.processType.maxDetailCount;
    }
  },
  onLoad() {
  },
  methods: {
	  checkboxInit(row,index){
      if(this.form.isDocumentCheck===true){
        return 1;
      }
		  if(row.isLocked==='1'){
			  return 0;
		  }else if(this.form.isIncludeCheckAsset===false){//不允许盘点的,通过任务数量判断是否可选
			  if(row.isTask===0){//任务数量为0的可选
				  return 1;
			  }else{//否则不可选
				  return 0;
			  }
		  }else{
			  return 1;
		  }
	  },
    async initData() {
    },
    //显示
    async open(entity) {
      this.form = Object.assign({}, entity);
	  //单据类型为报废时，添加本次盘亏的查询条件
      if(entity.documentType==='scrap'){
        if(this.searches.filter(item=>item.code==='queryHuaShiCheckRemark').length===0){
          this.searches.push({type: "switch", name: "本次盘亏(价值非0)", code: "queryHuaShiCheckRemark",ops:[false,true]});
          this.searchForm = {queryHuaShiCheckRemark:false};
          this.form.queryHuaShiCheckRemark = this.searchForm.queryHuaShiCheckRemark;
        }
      }
	  //闲置调入时，设置部门的查询范围
      if(entity.processTypeCode==='XZDR'){
          this.searches.forEach(item=>{
			//使用部门的查询范围，为排除部门范围
            if(item.code==='usingDepartmentId'){
              item.dataRange="excludeOrgRange";//排除部门范围
            }
          });
          let innerRangeDeptIds = this.$TOOL.current.innerRangeDeptIds();//所在部门范围内的部门id
          let allDeptOptions = await this.$cache.dic.options("SysOrganization", true);
          let allDeptIds = [];
		  //查询所有部门，并取所在部门范围之外的其它部门id
          if(allDeptOptions&&Array.isArray(allDeptOptions)){
            allDeptOptions.forEach(item=>{
              if(!innerRangeDeptIds.includes(item.value)){
                allDeptIds.push(item.value);
              }
            });
          }
		  //如果没有其它部门，则设置为一默认的none值，使用查询的数据为空
          if(allDeptIds.length===0){
            allDeptIds.push("none")
          }
        //  console.log("innerRangeDeptIds",innerRangeDeptIds)
        //  console.log("allDeptIds",allDeptIds)
          this.form.deptIds = allDeptIds;
      }
      this.oldForm = this.$TOOL.objCopy(this.oldForm);
      this.visible = true;
      this.resetHandler();
      this.initData();
    },
    async close(){
      //this.$refs.assetselecter.onClose();
      this.visible = false;
    },
    async searchHandler() {
	  //搜索时，根据本次盘亏(价值非0)的查询标志，动态显示盘亏备注列
	  let state = 0;
	  if(this.form.documentType==='scrap'){
		  this.form.queryHuaShiCheckRemark = this.searchForm.queryHuaShiCheckRemark;
		  if(this.searchForm.queryHuaShiCheckRemark===true){
			  if(this.columns.filter(item=>item.code==='other.huaShiCheckRemark').length===0){
				  this.columns.splice(1,0,{code: "other.huaShiCheckRemark", name: "盘亏备注", width:"150",align:"center"});
				  this.elk++;
				  state = this.elk;
			  }
		  }else{
			  if(this.columns.filter(item=>item.code==='other.huaShiCheckRemark').length===1){
				  this.columns.splice(1,1);
				  this.elk++;
				  state = this.elk;
			  }
		  }
	  }
	  if(state===0){
		  await this.$refs.assetSelecterTable.refresh(this.searchForm);
	  }
    },
    resetHandler() {
	  if(this.form.documentType&&this.form.documentType==='scrap'){
		  this.searchForm = {queryHuaShiCheckRemark:false};
	  }else{
		  this.searchForm = {};
	  }
    },
    columnClickHandler(name,data){
      this.$options.methods[name](this, data);
    },
    //查看
    async showAsset(_this, row) {
      let assetCategory = await _this.$cache.data.loadAssetCategory(row.assetCategoryId);
      try {
        _this.loading = true;
        let entity = {cardId: assetCategory.assetCardId, _editFlag: false}
        _this.$nextTick(() => {
          _this.cardPreview = false;
          _this.$refs.dataCard.open(Object.assign(entity, row));
        });
      } finally {
        _this.loading = false;
      }
    },
     //查看
     async showDocument(_this, row) {
      if(row.documentDetailId!=null){
        try {
          _this.loading = true;
          let res = await _this.$API.asset.assetLog.findById.post({id: row.documentDetailId});
          if (res.code === 2000) {
               _this.$nextTick(() => {
                    _this.$router.push({name:"documentPrepare",params:{fromRouteId:_this.$TOOL.crypto.MD5(_this.$route.path),configId:res.data.documentInfo.documentConfigId,id:res.data.documentInfo.id}});
                  })
            }
        } finally {
          _this.loading = false;
        }
      }
    },

    //保存
    async save() {
      let selections = this.$refs.assetSelecterTable.selections();
      if (selections.length === 0) {
        let confirm = await this.$confirm('是否全部选择?', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
        if (!confirm) return;
        this.loading = true;
        let queryParams= this.$refs.assetSelecterTable.queryParams(this.searchForm);

        //引入分页的参数
				queryParams = Object.assign(queryParams, this.pageForm);
        queryParams = this.$TOOL.objCopy(queryParams);
        //如果不是盘点操作，则只查询未锁定的资产
        if(this.form.isDocumentCheck!==true){
            queryParams.isLocked='0';
            if(this.form.isIncludeCheckAsset===false){
              queryParams.isTask=0;
            }
        }

        //请求数据加载
				let rsp = await http.post(this.$API.asset.asset.selectAssetIds.url, queryParams);
        //  console.log(rsp);
				if (rsp.code===2000) {
            this.loading = false;
            let assetIds = rsp.data;
            if(Array.isArray(assetIds)){
              assetIds.forEach(assetId=>{
                this.ids.push(assetId);
              });
            }
            if(this.ids.length===0){
              this.$message.warning('没有符合条件的资产可用');
              return ;
            }
        }else{
          this.loading = false;
          return ;
        }
      }else{

      let confirm = await this.$confirm('请确认是否提交选择的资产', '提示', {type: 'warning'}).then(() => {return true;}).catch(() => {return false;});
      if (!confirm) return;

      selections.forEach(row=>{
        this.ids.push(row.id);
      });
    }

      this.$emit('success');
      this.visible = false;
    },
  }
}
</script>

<style scoped>
h2 {
  font-size: 17px;
  color: #3c4a54;
  padding: 0 0 30px 0;
}

[data-theme="dark"] h2 {
  color: #fff;
}

::v-deep(.dialogselect .el-dialog__header){
  padding: 0px !important;
  margin-right: 0px;
}
::v-deep(.dialogsearch){
 padding-top: 10px;
}

::v-deep(.dialogsearch .el-form-item--default .el-form-item__label){
  font-size: 13px !important;
  color: rgb(101, 101, 101) !important;
}

::v-deep(.dialogsearch .el-form-item--default .el-input__inner,.dialogsearch .el-form-item--default .el-date-editor){
  font-size: 13px !important;

}




/*el-dialog__body el-container el-main*/
/* el-dialog__header exDialogHeader */

</style>
